import json
import logging
import time
from login import login
from config import db
from wechat_user.WXBizDataCrypt import WXBizDataCrypt
from wechat_user.models import USER,Mark,Class
import requests


appId = 'wxc0beabed23e2573a'
class user():
    @staticmethod
    def get_sessionid(code=None, key=None, iv=None):
        url = 'https://api.weixin.qq.com/sns/jscode2session'
        data = {
            'appid' : 'wxc0beabed23e2573a',
            'secret' : '4c343811a48869edc6558091ed21860b',
            'js_code' : code,
            'grant_type' : 'authorization_code',
        }
        header: {
        'content - type': 'application / json'
        }
        r = requests.post(url=url,data=data)
        state = json.loads(r.text)
        return state

    @staticmethod
    def get_user_info(code=None, key=None, iv=None):
        is_bind = ''
        res = user.get_sessionid(code=code)
        logging.error(res)
        openid = res['openid']
        session_key = res['session_key']
        # unionid = res['unionid']
        tmp = WXBizDataCrypt(appId, session_key)
        ret = tmp.decrypt(key, iv)
        logging.error(ret)
        filter = USER.query.filter(USER.openid == openid).first()
        if not filter:
            add = USER(openid=ret['openId'], nickName=ret['nickName'], avatarUrl=ret['avatarUrl'], gender=ret['gender'], province=ret['province'],city=ret['city'],country=ret['country'])
            db.session.add(add)
            db.session.commit()
        else:
            if filter.sno and filter.spw:
                is_bind = 1
                ret['sno'] = filter.sno
            if filter.avatarUrl == ret['avatarUrl'] and filter.nickName == ret['nickName'] and filter.gender == ret[
                'gender']:
                pass
            else:
                filter.avatarUrl = ret['avatarUrl']
                filter.nickName = ret['nickName']
                filter.gender = ret['gender']
                filter.update_time = int(time.time())
                db.session.commit()
        ret['is_bind'] = is_bind
        return dict(data=ret,status=200)

    @staticmethod
    def bind(openid=None, sno=None, spw=None):
        filter = USER.query.filter(USER.openid == openid).first()
        filter.sno = int(sno)
        filter.spw = spw
        db.session.commit()
        res = login(sno=sno,spw=spw,do='login')
        if res:
            return True

    @staticmethod
    def get_mark(sno=None,spw=None,openid=None,do=None,year=None,term=None):
        if not do:
            dic = login(sno=sno,spw=spw,do=do,year=year,term=term)
            dic = json.loads(dic)
            print(dic)
        # mark = get_grade(login_session=dic['login_session'], now_url=dic['now_url'], login_soup=dic['login_soup'], send_header=['send_header'])
            grade = dic['grade_json']['grade']
            info = dic['info_json']
            courses = dic['schedule_json']['courses']
            if info:
                filter = USER.query.filter(USER.openid == openid).first()
                filter.name = info['name']
                filter.college = info['college']
                filter.cla = info['class']
                filter.prof = info['prof']
                filter.birth = info['birth']
                filter.grade = info['grade']
                roles_id = filter.id
                # db.session.add(filter)
                db.session.commit()
                if grade:
                    for g in grade:
                        gg = Mark(roles_id=roles_id,openid=openid,grade=g['grade'],experiment=g['experiment'],final=g['final'],
                                  mid=g['mid'],usually=g['usually'],point=g['point'],credit=g['credit'],cname=g['cname'],
                                  semester=int(g['semester']),year=g['year'])
                        db.session.add(gg)
                        db.session.commit()
                if courses:
                    for c in courses:
                        cc = Class(roles_id=roles_id,openid=openid,type=int(c['type']),start=int(c['start']),end=int(c['end']),day_week=int(c['day_week']),
                                   cour_start=int(c['cour_start']),cour_length=int(c['cour_length']),cour_name=c['cour_name'],teacher_name=c['teacher_name'],
                                   cour_where=c['cour_where'],jud=int(c['jud']),year=year,term=term)
                        db.session.add(cc)
                        db.session.commit()

        return True

    @staticmethod
    def mark(openid=None):
        filter = Mark.query.filter(Mark.openid == openid).all()
        logging.error(openid)
        logging.error(filter)
        data = []
        for fil in filter:
            logging.error(fil)
            tmp = {
            "year": fil.year,
            "term": fil.semester,
            "cname": fil.cname,
            "credit": fil.credit,
            "point": fil.point,
            "usually": fil.usually,
            "mid": fil.mid,
            "final": fil.final,
            "experiment": fil.experiment,
            "grade": fil.grade
            }
            data.append(tmp)
        # user = USER.query.filter(USER.openid == openid).first()
        # user_info = {
        #     'name':user.name,
        #     'sno':user.sno,
        #     'calss':user.cla,
        #     'grade':user.grade
        # }
        return data

if __name__ == '__main__':
    # user.get_user_info(code="0a1TOWTG06qthg2llrSG0iF9UG0TOWT4",key='p3oCbRh6wo6WF+9hPVC5fq557AVyKhLwLvhnqRGzkm8bcnMB5D…3KRoPOPWHlopupCVqb0bASts/ipKU4++9eILG7vm636fsDg==',iv="RcHd7cSEKPNWaNzAQj+s2A==")
    # filter = USER.query.filter(USER.openid == '12233').first()
    # print(filter)
    print(user.mark(openid='ouyx45J6A38daaLFYqkL50JMMb5k'))